// 手写 Promise.all
function fn1() {
  function myPromiseAll(ps) {
    const results = new Array(ps.length).fill(null);

    return new Promise((resolve, reject) => {
      for (let i = 0; i < ps.length; i++) {
        const p = ps[i];

        p.then((value) => {
          results[i] = value;

          /* 最慢的promise成功以后 results中没有null 整体就可以履约了 */
          results.indexOf(null) === -1 && resolve(results);
        }).catch((err) => {
          reject(err);
        });
      }
    });
  }

  myPromiseAll([
    Promise.resolve(1),
    new Promise((resolve, reject) => setTimeout(resolve, 3000, "good luck")),
    new Promise((resolve, reject) => setTimeout(resolve, 2000, 3)),
  ])
    .then((values) => console.log("success", values))
    .catch((err) => console.log("failed", err));
}

// 手写apply 函数
function fn2() {
  Function.prototype.myApply = function (thisArg, args) {
    console.log("this in myApply", this); //add
    thisArg.fn = this;
    const ret = thisArg.fn(...args);
    delete thisArg.fn;
    return ret;
  };

  function add(a, b) {
    console.log("add this=", this); //?
    return a + b;
  }

  const obj = { name: "张三" };
  console.log(add.myApply(obj, [2, 3])); //张三 5
  console.log(obj); //张三
}

// 函数的柯里化
// 实现 add(1)(2,3,4)(5,6)
function fn3() {
  function curry(fn) {
    // console.log(fn.length); //函数的参数列表长度 6
    let totalArgs = [];

    return function cfn(...args) {
      totalArgs = totalArgs.concat(args);
      console.log("totalArgs=", totalArgs);

      if (totalArgs.length === fn.length) {
        const ret = fn.apply(null, totalArgs);
        totalArgs = [];
        return ret;
      }

      // return function (...moreArgs) {
      //   console.log(moreArgs);
      //   return cadd(...moreArgs);
      // };

      return cfn;
    };
  }

  function add(a, b, c, d, e, f) {
    return a + b + c + d + e + f;
  }

  let cadd = curry(add);
  console.log(cadd(1, 2, 3, 4, 5, 6)); //21

  cadd = curry(add);
  console.log(cadd(1, 2, 3)(4, 5)(6)); //21
}

// 循环打印红黄绿,红3秒-黄1秒-绿3秒-黄1,循环往复
function fn4() {
  const red = () => console.log("red");
  const yellow = () => console.log("yellow");
  const green = () => console.log("green");

  async function loop(tasks) {
    for (let { task, duration } of tasks) {
      task();
      await new Promise((resolve) => setTimeout(resolve, duration));
    }

    loop(tasks);
  }

  loop([
    { task: green, duration: 3000 },
    { task: yellow, duration: 1000 },
    { task: red, duration: 3000 },
    { task: yellow, duration: 1000 },
  ]);
}

// 查找文章中出现频率最高的单词
function fn5() {
  const str = `
    when i was young i'd listen to the radio, 
    waiting for my favorite songs, 
    when it played i'd sing along, 
    it made me smile.
    it was such a happy time and not so long ago,
    how i wondered where they'd gone,
    but they're back again just like a long lost friend,
    all the songs i loved so well.
    every sha la la la every woo woo woo oh still shine
    `;

  const regWord = /[\w']+/g;
  const arr = str.match(regWord);
  // console.log(arr);

  const map = new Map();
  arr.forEach((w, i) =>
    map.get(w) ? map.set(w, map.get(w) + 1) : map.set(w, 1)
  );
  console.log(map);

  Array.from(map.entries()).forEach(([k, v]) => console.log(k, v));
  Array.from(map.entries())
    .sort((a, b) => b[1] - a[1])
    .forEach((e) => console.log(e));
}

// 实现日期格式化函数
function fn6() {
  const dateFormat = (dateInput, format) => {
    var day = dateInput.getDate();
    var month = dateInput.getMonth() + 1;
    var year = dateInput.getFullYear();
    format = format.replace(/yyyy/, year);
    format = format.replace(/MM/, month);
    format = format.replace(/dd/, day);
    return format;
  };

  console.log(dateFormat(new Date("2020-12-01"), "yyyy/MM/dd"));
  console.log(dateFormat(new Date("2020-04-01"), "MM/dd/yyyy"));
  console.log(dateFormat(new Date("2020-04-01"), "yyyy年MM月dd日"));
}

// 实现负大整数相加
function fn7() {
  function bigAdd(a = "", b = "") {
    a = a.slice(1);
    b = b.slice(1);

    const len = a.length >= b.length ? a.length : b.length;
    let retStr = "";

    let cplus = 0;
    for (let i = 1; i <= len; i++) {
      const at = a.length - i >= 0 ? Number(a[a.length - i]) : 0;
      const bt = b.length - i >= 0 ? Number(b[b.length - i]) : 0;

      //   const ct = at + bt < 10 ? at + bt : (at + bt) % 10 ;
      let ct;
      if (at + bt + cplus < 9) {
        ct = at + bt + cplus;
        cplus = 0;
      } else {
        ct = (at + bt + cplus) % 10;
        cplus = 1;
      }
      console.log(at, bt, cplus, ct);

      retStr = ct + retStr;
    }

    return `-${cplus || ""}${retStr}`;
  }

  console.log(bigAdd("-99999999999999999999999", "-9999999999999999")); //-1098
  console.log(bigAdd("-12", "-34")); //-46
  console.log(bigAdd("-99", "-34")); //-133
  console.log(bigAdd("-0", "-0")); //-0
  console.log(bigAdd("-0", "-26")); //-26
}

(function main() {
  // fn1();
  // fn2();
  // fn3();
  fn4();
  // fn5();
  // fn6();
  // fn7();
})();
